package com.evil.application.pojo.dto.form;

import com.evil.application.enums.form.control.ControlCodeEnum;
import com.evil.application.pojo.dto.form.control.code.ControlDTO;
import com.evil.common.application.dto.form.ApplicationFormDTO;
import com.evil.common.core.enums.BaseEnum;
import com.evil.common.family.enums.RCodeEnum;
import com.evil.common.core.exception.BusinessException;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 编辑应用表单控件 请求实体
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class ModifyApplicationFormControlReqDTO extends ApplicationFormDTO {

    private List<Map<String, Object>> controlList = new ArrayList<>();

    public List<ControlDTO> getControlList() {
        return this.initControlDTO(controlList, new HashSet<>());
    }

    private List<ControlDTO> initControlDTO(List<Map<String, Object>> controlList, Set<String> controlFieldSet) {
        return controlList.stream()
                .map(e -> {
                    ControlDTO controlDTO = ControlCodeEnum.caseControlRespDTO(e);

                    if (!controlFieldSet.add(controlDTO.getControlField())) {
                        throw new BusinessException(BaseEnum.ERROR_PARAMETER, "字段名称重复");
                    }
                    // 处理子控件
                    Object obj = e.get(ControlDTO.CHILD_CONTROLS);
                    if (obj instanceof List) {
                        List<?> childObj = (List<?>) obj;
                        if (!childObj.isEmpty()) {
                            List<Map<String, Object>> childControls = childObj.stream()
                                    .filter(c -> c instanceof Map)
                                    .map(c -> {
                                        Map<?, ?> children = (Map<?, ?>) c;
                                        Map<String, Object> childrenMap = new HashMap<>();
                                        children.forEach((key, value) -> {
                                            if (null != key) {
                                                childrenMap.put(key.toString(), value);
                                            }
                                        });
                                        return childrenMap;
                                    })
                                    .collect(Collectors.toList());
                            controlDTO.setChildControls(this.initControlDTO(childControls, controlFieldSet));
                        }
                    }
                    return controlDTO;
                })
                .collect(Collectors.toList());
    }
}
